package com.tao.auto.batchtao.home.schedue;

import com.tao.auto.batchtao.database.dao.MgtUserInfoRepository;
import com.tao.auto.batchtao.database.entity.MgtUserInfo;
import com.tao.auto.batchtao.home.AbstractHomeRegisterBaseFlow;
import com.tao.auto.batchtao.home.account.HomeAccountQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class LoginSignSchedue {

    public AtomicBoolean flag = new AtomicBoolean(true);
    public AtomicBoolean flagLogin = new AtomicBoolean(true);
    @Autowired
    private MgtUserInfoRepository mgtUserInfoRepository;
    @Autowired
    private AbstractHomeRegisterBaseFlow abstractHomeRegisterBaseFlow;

    @Scheduled(cron = "0 0 9 * * ?")
    public void login() {
        //查数据库 定时签到
        int page = 0;
        List<MgtUserInfo> mgtUserInfos;
        try {
            while (!(mgtUserInfos = mgtUserInfoRepository.findAll(PageRequest.of(page++, 100)).getContent()).isEmpty() && flagLogin.get()) {
                mgtUserInfos.forEach(mgtUserInfo -> {
                    try {
                        TimeUnit.SECONDS.sleep(3);
                        HomeAccountQueue.queue.put(mgtUserInfo);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (Exception e) {

        }
    }

    public void register() throws InterruptedException {
        while (flag.get()) {
            TimeUnit.SECONDS.sleep(10);
            try {
                abstractHomeRegisterBaseFlow.doSomething(null);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Scheduled(cron = "0 0 20 * * ?")
    public void stopRegister() {
        flag.set(false);
    }

    //    @Scheduled(cron = "0 0 9 * * ?")
    public void startRegister() throws InterruptedException {
        flag.set(true);
        register();
    }

}
